import React, { useState, useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Card, List, Button, Radio, Input, Form, message, Typography, Divider } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { CartItem, Address, Order, OrderItem } from '../../types';
import { Storage, STORAGE_KEYS } from '../../utils/storage';

const { Title, Text } = Typography;
const { TextArea } = Input;

const CreateOrder: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [cartItems, setCartItems] = useState<CartItem[]>([]);
  const [addresses, setAddresses] = useState<Address[]>([]);
  const [selectedAddress, setSelectedAddress] = useState<string>('');
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    const items = location.state?.cartItems || [];
    setCartItems(items);
    
    // 模拟地址数据
    const mockAddresses: Address[] = [
      {
        id: '1',
        name: '张三',
        phone: '13800138000',
        province: '北京市',
        city: '北京市',
        district: '朝阳区',
        detail: '朝阳路123号',
        isDefault: true
      },
      {
        id: '2',
        name: '李四',
        phone: '13900139000',
        province: '上海市',
        city: '上海市',
        district: '浦东新区',
        detail: '陆家嘴金融中心456号',
        isDefault: false
      }
    ];
    setAddresses(mockAddresses);
    setSelectedAddress(mockAddresses[0]?.id || '');
  }, [location.state]);

  const getTotalPrice = () => {
    return cartItems.reduce((total, item) => total + item.product.price * item.quantity, 0);
  };

  const handleSubmitOrder = async (values: any) => {
    if (!selectedAddress) {
      message.error('请选择收货地址');
      return;
    }

    setLoading(true);
    
    try {
      // 模拟创建订单
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const selectedAddr = addresses.find(addr => addr.id === selectedAddress)!;
      const orderItems: OrderItem[] = cartItems.map(item => ({
        id: Date.now().toString() + Math.random(),
        productId: item.productId,
        product: item.product,
        quantity: item.quantity,
        price: item.product.price
      }));

      const order: Order = {
        id: Date.now().toString(),
        userId: '1',
        items: orderItems,
        totalAmount: getTotalPrice(),
        status: 'pending',
        address: selectedAddr,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      };

      // 保存订单
      const orders = Storage.get<Order[]>(STORAGE_KEYS.ORDERS) || [];
      orders.unshift(order);
      Storage.set(STORAGE_KEYS.ORDERS, orders);

      // 清空购物车中的已下单商品
      const cart = Storage.get<CartItem[]>(STORAGE_KEYS.CART) || [];
      const remainingCart = cart.filter(cartItem => 
        !cartItems.some(orderItem => orderItem.id === cartItem.id)
      );
      Storage.set(STORAGE_KEYS.CART, remainingCart);

      message.success('订单创建成功');
      navigate(`/payment/${order.id}`);
    } catch (error) {
      message.error('订单创建失败');
    } finally {
      setLoading(false);
    }
  };

  if (cartItems.length === 0) {
    return (
      <div style={{ textAlign: 'center', padding: '50px 0' }}>
        <Text>没有商品信息</Text>
        <br />
        <Button type="primary" onClick={() => navigate('/')}>返回首页</Button>
      </div>
    );
  }

  return (
    <div style={{ maxWidth: 800, margin: '0 auto' }}>
      <Title level={2}>确认订单</Title>

      {/* 收货地址 */}
      <Card title="收货地址" style={{ marginBottom: 16 }}>
        <Radio.Group 
          value={selectedAddress} 
          onChange={(e) => setSelectedAddress(e.target.value)}
          style={{ width: '100%' }}
        >
          {addresses.map(address => (
            <Radio key={address.id} value={address.id} style={{ width: '100%', marginBottom: 16 }}>
              <div>
                <Text strong>{address.name} {address.phone}</Text>
                {address.isDefault && <Text type="secondary"> [默认]</Text>}
                <br />
                <Text type="secondary">
                  {address.province} {address.city} {address.district} {address.detail}
                </Text>
              </div>
            </Radio>
          ))}
        </Radio.Group>
        <Button type="dashed" icon={<PlusOutlined />} style={{ width: '100%', marginTop: 16 }}>
          添加新地址
        </Button>
      </Card>

      {/* 商品信息 */}
      <Card title="商品信息" style={{ marginBottom: 16 }}>
        <List
          dataSource={cartItems}
          renderItem={(item) => (
            <List.Item>
              <List.Item.Meta
                avatar={
                  <img
                    src={item.product.image}
                    alt={item.product.name}
                    style={{ width: 60, height: 60, objectFit: 'cover', borderRadius: 4 }}
                  />
                }
                title={item.product.name}
                description={
                  <div>
                    <Text>单价: ¥{item.product.price}</Text>
                    <br />
                    <Text>数量: {item.quantity}</Text>
                  </div>
                }
              />
              <div>
                <Text className="price-current">
                  ¥{(item.product.price * item.quantity).toFixed(2)}
                </Text>
              </div>
            </List.Item>
          )}
        />
      </Card>

      {/* 订单信息 */}
      <Card title="订单信息">
        <Form form={form} onFinish={handleSubmitOrder} layout="vertical">
          <Form.Item label="订单备注" name="remark">
            <TextArea rows={3} placeholder="选填，对本次订单的说明" />
          </Form.Item>

          <Divider />

          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div>
              <Text>共 {cartItems.length} 件商品</Text>
            </div>
            <div>
              <Text style={{ fontSize: 18 }}>
                合计: <span className="price-current">¥{getTotalPrice().toFixed(2)}</span>
              </Text>
            </div>
          </div>

          <Form.Item style={{ marginTop: 24, textAlign: 'right' }}>
            <Button size="large" onClick={() => navigate(-1)} style={{ marginRight: 16 }}>
              返回
            </Button>
            <Button type="primary" size="large" htmlType="submit" loading={loading}>
              提交订单
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default CreateOrder;
